package acs.util;

import java.util.HashMap;
import java.util.Map;

public class CacheUtil {
	private Map<String,Object> cache=new HashMap<>();

	private volatile boolean  isUpdate=false;
	private static long TIME_OUT=1 * 1000;
	
	static CacheUtil instance=new CacheUtil();
	
	public static CacheUtil getInstance() {
		return instance;
	}
	
	private CacheUtil() {}
	
	public void saveCache(Map<String,Object> cache) {
		isUpdate=true;
		try {
			System.out.println("保存缓存中，清稍后。。。");
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		this.cache=cache;
		System.out.println("保存缓存成功");
		isUpdate=false;
	}
	
	public void updateCache(Map<String,Object> cache) {
		System.out.println("更新缓存");
	}
	
	public void removeCache() {
		cache.clear();
		System.out.println("移除缓存");
	}
	
	public void removeCache(String key) {
		cache.remove(key);
		System.out.println("移除:"+key+"缓存");
	}
	
	public Object getCache(String key) {
		long startTime = System.currentTimeMillis();
		while(isUpdate) {
			//这里可以自旋或者返回抄底数据
			if(isTimeOut(startTime)) {
				System.out.println("超时了，跳出自旋");
				break;
			}
		}
		if(isUpdate) {
			return null;
		}
		System.out.println("线程名："+Thread.currentThread().getName()+"查询key为:"+key+"，的缓存");
		return cache.get(key);
		
	}
	//判定是否超时
	private boolean isTimeOut(long beginMillis) {
		long diff = System.currentTimeMillis() - beginMillis;
		return diff > TIME_OUT;
	}
	
}
